package com.ringtheweb.web.action;

import org.jboss.seam.ScopeType;
import org.jboss.seam.annotations.In;
import org.jboss.seam.annotations.Logger;
import org.jboss.seam.annotations.Name;
import org.jboss.seam.annotations.Out;
import org.jboss.seam.bpm.Actor;
import org.jboss.seam.faces.FacesMessages;
import org.jboss.seam.log.Log;
import org.jboss.seam.security.Credentials;
import org.jboss.seam.security.Identity;

import com.ringtheweb.model.Role;
import com.ringtheweb.model.User;
import com.ringtheweb.persistence.dao.IUserDAO;


@Name("authenticator")
public class AuthenticatorAction {
	@Logger
	Log log;
	
	@In
	Identity identity;
	
	@In Credentials credentials;
	
	@In Actor actor;
	
	@In("#{userDAO}") IUserDAO userDAO;
	
    @Out(required=false,scope=ScopeType.SESSION)
    private User user;

	public boolean authenticate() {
		log.info("authenticating #0", credentials.getUsername());
		
		user = userDAO.findByLoginAndPassword(credentials.getUsername(),
				credentials.getPassword());
		if (user == null) {
			FacesMessages.instance().add("Invalid username/password");
			return false;
		}

		if (user.getRoles() != null) {
			for (Role mr : user.getRoles())
				identity.addRole(mr.getName());
		}
		
		actor.setId(user.getLoginName());

		for(Role role : user.getRoles()) {
			actor.getGroupActorIds().add(role.getName());
		}

		return true;
	}
	
	
    public String logout() {
        Identity.instance().logout();
        return "loggedOut";
    }
}
